package api

import (
	"django_blog_gin/internal/dto"
	"django_blog_gin/internal/repository"
	"django_blog_gin/internal/svc"
	"django_blog_gin/internal/utils"
	"strings"

	"github.com/gin-gonic/gin"
)

type EsBlogArticleController struct {
	svcCtx *svc.ServiceContext
}

func NewEsBlogArticleController(svcCtx *svc.ServiceContext) *EsBlogArticleController {
	return &EsBlogArticleController{svcCtx: svcCtx}
}

func (i *EsBlogArticleController) SearchEsBlogArticle(ctx *gin.Context) {
	var req dto.EsSearchArticleReq

	if err := ctx.ShouldBindJSON(&req); err != nil {
		utils.ResponseError(ctx, 400, err.Error())
		return
	}
	utils.SetDefaults(&req)
	repo := repository.NewEsArticleRepo(i.svcCtx)
	articleList, err := repo.SearchDoc(req)
	if err != nil {
		utils.ResponseError(ctx, 400, err.Error())
		return
	}
	respList := make([]dto.ArticleWithTagsResp, 0, len(articleList))
	for _, a := range articleList {
		respList = append(respList, dto.ArticleWithTagsResp{
			BlogArticleWithTags: a,
			CreatedTime:         a.CreatedTime.Format("2006-01-02 15:04:05"),
			LastModTime:         a.LastModTime.Format("2006-01-02 15:04:05"),
			PubTime:             a.PubTime.Format("2006-01-02 15:04:05"),
			Tags:                strings.Split(a.Tags, ","),
		})
	}
	utils.ResponseSuccess(ctx, respList, "ok")
}
